<template>
  <div ref="chartBoxParent" style="width: 100%">
    <div id="box" ref="chartBox" class="chartBox-box" :style="{ height: height + 'px' }"></div>
  </div>
</template>

<script setup lang="ts">
import { ECharts, EChartsOption } from 'echarts';
import ChartOptionInit from './options';
import useEcharts from '@/composables/useEcharts';
import { computed, watch, onBeforeUnmount, onMounted, ref, toRefs, watchEffect } from 'vue';

import { debounce } from 'lodash-es';

const props = defineProps({
  chartType: {
    type: String,
    required: true,
  },
  options: {
    type: Object,
    default: null,
  },
});
const { chartType, options } = toRefs(props);

const emits = defineEmits(['handel']);
const chartBoxParent = ref<HTMLElement>();
const height = ref();
const width = ref();
const chartBox = ref<HTMLElement>();
const op = computed<EChartsOption>(() => {
  return {
    ...options.value,
  };
});
let echart: ECharts;
const resizeHandler = debounce(() => {
  echart.resize();
}, 100);
watch(options, () => {});
onMounted(() => {
  height.value = chartBoxParent.value?.clientHeight;
  width.value = chartBoxParent.value?.clientWidth;

  setTimeout(function () {
    const { setOptions, ec } = useEcharts(chartBox.value!);
    echart = ec;

    window.addEventListener('resize', resizeHandler);

    setOptions(ChartOptionInit[chartType.value]);
    watchEffect(() => {
      if (Object.keys(op.value).length === 0) {
        return;
      }
      setOptions(op.value);
    });
    ec.off('click');
    ec.on('click', function (e) {
      emits('handel', e.name);
    });
  }, 100);
});
onBeforeUnmount(() => {
  echart.dispose();
  window.removeEventListener('resize', resizeHandler);
});
</script>

<style scoped lang="scss">
#chartBox-box {
  width: 100%;
}
#chartBox-box > div {
  width: 100% !important;
}
</style>
